package controllers

import (
	"encoding/json"
	"github.com/tealeg/xlsx"
	"ltbz/cultural_tourism_api/models"
	"ltbz/cultural_tourism_api/utils"
	"os"
	"time"
)

// 操作员管理
type OperatorController struct {
	BaseAuthController
}

// @Title 添加操作员
// @Description 添加操作员
// @Param	request	body models.OperatorAddReq true "type json string"
// @Success 200
// @router /add [post]
func (this *OperatorController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.OperatorAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.RealName == "" {
		br.Msg = "姓名不能为空"
		return
	}
	if req.Mobile == "" {
		br.Msg = "手机号不能为空"
		return
	}
	if req.ScenicSpotId <= 0 {
		br.Msg = "请选择景区"
		return
	}
	if req.Password == "" {
		br.Msg = "请输入密码"
		return
	}

	obj := new(models.Operator)
	count, err := obj.GetOperatorExist(req.Mobile, 0)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,判断手机号是否存在失败,Err:" + err.Error()
		return
	}

	if count > 0 {
		br.Msg = "手机号已存在，请重新输入"
		return
	}
	nowStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	uuid := utils.MD5(time.Now().Format(utils.FormatDateTimeUnSpace) + utils.GetRandString(16))
	token := utils.MD5(nowStr + utils.GetRandString(32))
	obj.Mobile = req.Mobile
	obj.RealName = req.RealName
	obj.ScenicSpotId = req.ScenicSpotId
	obj.OperatorStatus = "启用"
	obj.Uuid = uuid
	obj.AppToken = token
	obj.Password = utils.MD5(req.Password + uuid)
	obj.CreateTime = time.Now()
	obj.ModifyTime = time.Now()
	err = obj.AddOperator()
	if err != nil {
		br.ErrMsg = "保存失败，Err:" + err.Error()
		br.Msg = "保存失败"
		return
	}
	br.Msg = "保存成功"
	br.Ret = 200
	return
}

// @Title 编辑操作员
// @Description 编辑操作员
// @Param	request	body models.OperatorEditReq true "type json string"
// @Success 200
// @router /edit [post]
func (this *OperatorController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.OperatorEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.OperatorId <= 0 {
		br.Msg = "参数错误"
		return
	}

	if req.RealName == "" {
		br.Msg = "姓名不能为空"
		return
	}
	if req.Mobile == "" {
		br.Msg = "手机号不能为空"
		return
	}
	if req.ScenicSpotId <= 0 {
		br.Msg = "请选择景区"
		return
	}

	obj := new(models.Operator)
	count, err := obj.GetOperatorExist(req.Mobile, req.OperatorId)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,判断手机号是否存在失败,Err:" + err.Error()
		return
	}

	if count > 0 {
		br.Msg = "手机号已存在，请重新输入"
		return
	}

	updateParams := make(map[string]interface{})
	updateParams["real_name"] = req.RealName
	updateParams["mobile"] = req.Mobile
	updateParams["scenic_spot_id"] = req.ScenicSpotId
	updateParams["modify_time"] = time.Now()

	whereParam := make(map[string]interface{})
	whereParam["scenic_spot_id"] = req.ScenicSpotId

	err = obj.Update(updateParams, whereParam)
	if err != nil {
		br.ErrMsg = "保存失败，Err:" + err.Error()
		br.Msg = "保存失败"
		return
	}
	br.Msg = "保存成功"
	br.Ret = 200
	return
}

// @Title 启用/禁用操作员
// @Description 启用/禁用操作员
// @Param	request	body models.OperatorEnableOrDisableReq true "type json string"
// @Success 200
// @router /enable_or_disable [post]
func (this *OperatorController) EnableOrDisable() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.OperatorEnableOrDisableReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.OperatorId <= 0 {
		br.Msg = "参数错误"
		return
	}

	obj := new(models.Operator)
	item, err := obj.GetOperatorById(req.OperatorId)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}

	updateParams := make(map[string]interface{})
	if item.OperatorStatus == "禁用" {
		updateParams["operator_status"] = "启用"
	} else {
		updateParams["operator_status"] = "禁用"
	}

	updateParams["modify_time"] = time.Now()

	whereParam := make(map[string]interface{})
	whereParam["operator_id"] = req.OperatorId

	err = obj.Update(updateParams, whereParam)
	if err != nil {
		br.ErrMsg = "保存失败，Err:" + err.Error()
		br.Msg = "保存失败"
		return
	}
	br.Msg = "保存成功"
	br.Ret = 200
	return
}

// @Title 获取操作员列表
// @Description 获取操作员列表
// @Param	request	body models.OperatorListReq true "type json string"
// @Success 200 {object} models.OperatorPageResp
// @router /list [post]
func (this *OperatorController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	body := this.Ctx.Input.RequestBody
	req := new(models.OperatorListReq)
	if string(body) != "" {
		err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	if req.PageSize <= 0 {
		req.PageSize = utils.PageSize20
	}
	if req.CurrentIndex <= 0 {
		req.CurrentIndex = 1
	}

	startSize := utils.StartIndex(req.CurrentIndex, req.PageSize)

	obj := new(models.Operator)

	var condition string
	var pars []interface{}

	if req.RealName != "" {
		scenicSpotName := `%` + req.RealName + `%`
		condition += "AND a.real_name LIKE ?"
		pars = append(pars, scenicSpotName)
	}

	if req.Mobile != "" {
		mobile := `%` + req.Mobile + `%`
		condition += "AND a.mobile LIKE ?"
		pars = append(pars, mobile)
	}

	if req.ScenicSpotId > 0 {
		condition += "AND a.scenic_spot_id = ?"
		pars = append(pars, req.ScenicSpotId)
	}

	total, err := obj.GetOperatorPageCount(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	list, err := obj.GetScenicSpotPage(condition, pars, startSize, req.PageSize)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	page := utils.GetPaging(req.CurrentIndex, req.PageSize, total)
	resp := new(models.OperatorPageResp)
	resp.List = list
	resp.Paging = page

	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = resp
	return
}

// @Title 修改密码
// @Description 修改密码
// @Param	request	body models.OperatorModifyPwdReq true "type json string"
// @Success 200
// @router /modify/pwd [post]
func (this *OperatorController) ModifyPwd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.OperatorModifyPwdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	obj := new(models.Operator)
	//查询账号是否存在
	operatorInfo, err := obj.GetOperatorById(req.OperatorId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "账号不存在！"
			br.ErrMsg = "账号不存在"
			return
		}
		br.Msg = "查询操作员信息失败！"
		br.ErrMsg = "查询操作员信息失败,Err:" + err.Error()
		return
	}

	if req.Pwd != req.ConfirmPwd {
		br.Msg = "新密码两次输入不一致，请核对！"
		br.ErrMsg = "新密码两次输入不一致，请核对"
		return
	}

	nowStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	token := utils.MD5(nowStr + utils.GetRandString(32))

	req.Pwd = utils.MD5(req.Pwd + operatorInfo.Uuid)

	if operatorInfo.Password == req.Pwd {
		br.Msg = "新密码不能与旧密码一致，请重试"
		br.ErrMsg = "新密码不能与旧密码一致，请重试"
		return
	}

	updateParams := make(map[string]interface{})
	whereParam := make(map[string]interface{})

	updateParams["password"] = req.Pwd
	updateParams["app_token"] = token
	updateParams["modify_time"] = time.Now().Format(utils.FormatDateTime)

	whereParam["operator_id"] = req.OperatorId

	err = obj.Update(updateParams, whereParam)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "修改成功"
	return
}

// @Title 获取核销记录列表
// @Description 获取核销记录列表
// @Param	request	body models.OperationRecordsReq true "type json string"
// @Success 200 {object} models.OperatorVerificationRecordsResp
// @router /verification_records [post]
func (this *OperatorController) VerificationRecords() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	body := this.Ctx.Input.RequestBody
	req := new(models.OperationRecordsReq)
	if string(body) != "" {
		err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	if req.PageSize <= 0 {
		req.PageSize = utils.PageSize20
	}
	if req.CurrentIndex <= 0 {
		req.CurrentIndex = 1
	}

	startSize := utils.StartIndex(req.CurrentIndex, req.PageSize)

	obj := new(models.Operator)

	var condition string
	var pars []interface{}

	condition += ` AND a.operator_id=? `
	pars = append(pars, req.OperatorId)

	if req.TradeCode != "" {
		condition += ` AND a.trade_code=? `
		pars = append(pars, req.TradeCode)
	}

	if req.WxUserId > 0 {
		condition += ` AND a.wx_user_id=? `
		pars = append(pars, req.WxUserId)
	}

	if req.GoodsCode != "" {
		condition += ` AND c.goods_code=? `
		pars = append(pars, req.GoodsCode)
	}

	if req.GoodsName != "" {
		condition += ` AND c.goods_name=? `
		pars = append(pars, req.GoodsName)
	}

	if req.Mobile != "" {
		mobile := `%` + req.Mobile + `%`
		condition += "AND a.mobile LIKE ?"
		pars = append(pars, mobile)
	}

	if req.VerificationStartTime != "" {
		condition += "AND b.verification_time >= ?"
		pars = append(pars, req.VerificationStartTime)
	}

	if req.VerificationEndTime != "" {
		condition += "AND b.verification_time <= ?"
		pars = append(pars, req.VerificationEndTime)
	}

	total, err := obj.GetOperatorVerificationRecordsCount(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	list, err := obj.GetOperatorVerificationRecordsList(condition, pars, startSize, req.PageSize)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	page := utils.GetPaging(req.CurrentIndex, req.PageSize, total)
	resp := new(models.OperatorVerificationRecordsResp)
	resp.List = list
	resp.Paging = page

	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = resp
	return
}

// @Title 核销记录导出
// @Description 核销记录导出
// @Param	request	body financial.OperationRecordsExportReq true "type json string"
// @Success 200
// @router /verification_records/export [get]
func (this *OperatorController) VerificationRecordsExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	body := this.Ctx.Input.RequestBody
	req := new(models.OperationRecordsExportReq)
	if string(body) != "" {
		err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	var condition string
	var pars []interface{}

	condition += ` AND a.operator_id=? `
	pars = append(pars, req.OperatorId)

	if req.TradeCode != "" {
		condition += ` AND a.trade_code=? `
		pars = append(pars, req.TradeCode)
	}

	if req.WxUserId > 0 {
		condition += ` AND a.wx_user_id=? `
		pars = append(pars, req.WxUserId)
	}

	if req.GoodsCode != "" {
		condition += ` AND c.goods_code=? `
		pars = append(pars, req.GoodsCode)
	}

	if req.GoodsName != "" {
		condition += ` AND c.goods_name=? `
		pars = append(pars, req.GoodsName)
	}

	if req.Mobile != "" {
		mobile := `%` + req.Mobile + `%`
		condition += "AND a.mobile LIKE ?"
		pars = append(pars, mobile)
	}

	if req.VerificationStartTime != "" {
		condition += "AND b.verification_time >= ?"
		pars = append(pars, req.VerificationStartTime)
	}

	if req.VerificationEndTime != "" {
		condition += "AND b.verification_time <= ?"
		pars = append(pars, req.VerificationEndTime)
	}

	obj := new(models.Operator)
	list, err := obj.GetOperatorVerificationRecordsListExport(condition, pars)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}

	style.Alignment = alignment
	style.ApplyAlignment = true
	if len(list) <= 0 {
		xlsxFile.AddSheet("暂无数据")
	}

	sheel, err := xlsxFile.AddSheet("智能桶用户")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}

	titleRow := sheel.AddRow()
	titleRow.AddCell().SetValue("序号")
	titleRow.AddCell().SetValue("景区名称")
	titleRow.AddCell().SetValue("订单编码")
	titleRow.AddCell().SetValue("用户ID")
	titleRow.AddCell().SetValue("手机号")
	titleRow.AddCell().SetValue("商品编码")
	titleRow.AddCell().SetValue("商品名称")
	titleRow.AddCell().SetValue("核销时间")
	for _, v := range list {
		dataRow := sheel.AddRow()
		dataRow.AddCell().SetValue(v.TradeId)
		dataRow.AddCell().SetValue(v.ScenicSpotName)
		dataRow.AddCell().SetValue(v.TradeCode)
		dataRow.AddCell().SetValue(v.WxUserId)
		dataRow.AddCell().SetValue(v.Mobile)
		dataRow.AddCell().SetValue(v.GoodsCode)
		dataRow.AddCell().SetValue(v.GoodsName)
		dataRow.AddCell().SetValue(v.VerificationTime)
	}
	pref := `核销记录_`
	savePath := `./temp/` + pref + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	err = xlsxFile.Save(savePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败,Err:" + err.Error()
		return
	}
	downloadFileName := pref + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	this.Ctx.Output.Download(savePath, downloadFileName)
	defer func() {
		os.Remove(savePath)
	}()
	br.Msg = "导出成功！"
	br.Ret = 200
}
